﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using SiteServer.Plugin;
using Dapper;
using System.Data.SqlClient;

namespace SS.LNDX.Service.Controllers
{
    [RoutePrefix("account")]
    public class AccountController : ApiController
    {
        private const string Route = "";
        public static SqlConnection conn => new SqlConnection(SiteServer.Plugin.Context.ConnectionString);

        [HttpPost, Route("login")]
        public IHttpActionResult Login(dynamic jsonModel)
        {
            try
            {
                string _mobile = jsonModel.mobile;
                string _userName = jsonModel.userName;

                if (Context.UserApi.IsMobileExists(_mobile))
                {
                    var user = Context.UserApi.GetUserInfoByMobile(_mobile);
                    string userName = user.UserName;
                    string displayName = user.DisplayName;

                    if (userName == _userName)
                    {
                        return Ok(displayName);
                    }
                    else
                    {
                        return InternalServerError(new Exception("姓名或手机号错误"));
                    }
                }
                else
                {
                    return InternalServerError(new Exception("姓名或手机号错误"));
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }

        }

        [HttpPost, Route("reset")]
        public IHttpActionResult ResetPassword(dynamic jsonModel)
        {
            try
            {
                string _userName = jsonModel.userName;
                string _password = jsonModel.password;
                string _citizenCode = jsonModel.citizenCode;

                //return Ok($"{jsonModel.userName}, {jsonModel.password}, {jsonModel.citizenCode}");

                if (Context.UserApi.IsUserNameExists(_userName))
                {
                    //用户名正确
                    var _user = Context.UserApi.GetUserInfoByUserName(_userName);

                    if (_user.GetString("CitizenCode") == _citizenCode)
                    {
                        //身份证号正确，执行密码重置
                        string error;
                        Context.UserApi.ChangePassword(_userName, _password, out error);
                        return Ok(error);
                    }
                    else
                    {
                        //身份证号错误，返回错误
                        return BadRequest("身份证号与用户名不匹配");
                    }
                }
                else
                {
                    //用户名不正确，返回错误
                    return BadRequest("用户名不存在");
                }

            }
            catch (Exception ex)
            {

                return InternalServerError(ex);
            }
        }

        [HttpPost, Route("modify")]
        public IHttpActionResult UpdateUser(dynamic jsonModel)
        {
            int _userId = jsonModel.id;
            string _displayName = jsonModel.displayName;
            string _mobile = jsonModel.mobile;
            string _citizenCode = jsonModel.citizenCode;

            var user = Context.UserApi.GetUserInfoByUserId(_userId);
            user.DisplayName = _displayName;
            user.Mobile = _mobile;
            user.SettingsXml = "{\"CitizenCode\": \"" + _citizenCode + "\"}";

            Context.UserApi.Update(user);

            return Ok("success");
        }

        [HttpGet, Route("{mobile}")]
        public IHttpActionResult Get([FromUri] string mobile)
        {
            try
            {
                if (Context.UserApi.IsMobileExists(mobile))
                {
                    string Mobile = Context.UserApi.GetUserInfoByMobile(mobile).Mobile;
                    string CitizenCode = Context.UserApi.GetUserInfoByMobile(mobile).DisplayName;
                    string Gender = Context.UserApi.GetUserInfoByMobile(mobile).Gender;

                    var result = new { value = Context.UserApi.GetUserInfoByMobile(mobile) };
                    return Ok(result);
                }
                else
                {
                    return InternalServerError(new Exception("fail"));
                }
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }


        }

        [HttpGet, Route("blacklist")]
        public IHttpActionResult GetBlackList()
        {
            try
            {
                string sql = $"SELECT * FROM siteserver_User where IsLockedOut='True'";
                return Ok(conn.Query<dynamic>(sql));
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpPost, Route("blacklist/delete/{id}")]
        public IHttpActionResult RemoveBlackList(int id)
        {
            try
            {
                string sql = $"UPDATE siteserver_User SET IsLockedOut = 'False' where Id={id}";
                conn.Query<dynamic>(sql);
                return Ok(new { msg = "success" });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet, Route("count")]
        public IHttpActionResult GetCount()
        {
            var request = Context.GetCurrentRequest();
            string sql = $"SELECT COUNT(*) FROM siteserver_User";
            
            return Ok(new { count = conn.QuerySingle<int>(sql) });
        }

        [HttpGet, Route("")]
        public IHttpActionResult GetList()
        {
            try
            {
                var request = Context.GetCurrentRequest();
                string siteId = request.GetQueryString("siteId");
                int pageSize = request.GetQueryInt("pageSize");
                int pageIndex = request.GetQueryInt("pageIndex", 1);
                string where = request.GetQueryString("where");
                string sort = request.GetQueryString("sort");
                string whereExpression = "1=1";
                string sortExpression = "ID DESC";

                if (!string.IsNullOrEmpty(siteId))
                {
                    whereExpression += $@" AND GroupId={siteId}"; //用表中的GroupId字段来存储SiteId以达到区分不同分校学院的目的
                }

                if (!string.IsNullOrEmpty(where))
                {
                    whereExpression += $@" AND Mobile = '{where}' OR DisplayName Like '%{where}%' OR SettingsXml Like '%{where}%'";
                }

                if (!string.IsNullOrEmpty(sort))
                {
                    sortExpression = sort;
                }

                //string sql = $"SELECT * FROM  siteserver_User WHERE {whereExpression} ORDER BY {sortExpression}";
                string sqlContents = $"SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY {sortExpression}) AS RowNum, * FROM siteserver_User WHERE {whereExpression} ) AS Details WHERE RowNum >= {pageIndex}*{pageSize}+1 AND RowNum <= {pageIndex + 1}*{pageSize}";
                string sqlCount = $"SELECT COUNT(*) FROM siteserver_User WHERE {whereExpression}";
                return Ok(new { count = conn.QuerySingle<int>(sqlCount), result = conn.Query<dynamic>(sqlContents) });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
            
        }
    }
}
